package com.arpa.wms.controller;

import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.dto.DeliveryDistributionDTO;
import com.arpa.wms.domain.entity.DeliveryDistribution;
import com.arpa.wms.domain.entity.Picking;
import com.arpa.wms.domain.entity.ReqPickMultiStockout;
import com.arpa.wms.domain.vo.DeliveryDistributionVO;
import com.arpa.wms.domain.vo.DeliveryItemVO;
import com.arpa.wms.service.IDeliveryDistributionService;
import com.arpa.wms.service.IPickingService;
import com.arpa.wms.service.WavePickingConfirmationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 出货分配 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-07
 */
@Api(tags = "出货分配")
@RestController
@RequestMapping(value="/deliveryDistribution", produces = "application/json;charset=UTF-8")
@Log4j2
public class DeliveryDistributionController  {

   @Autowired
   private IDeliveryDistributionService  iDeliveryDistributionService;

    @Autowired
    @Lazy
    private IPickingService pickingService;

    @Autowired
    private WavePickingConfirmationService wavePickingConfirmationService;

    /**
     * 获取 出货分配 列表
     *
     * @param deliveryDistributionDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 出货分配 列表", notes = "获取 出货分配 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DeliveryDistributionVO.class))
    @NeedLogin
    @GetMapping("/list")
    public Result list(DeliveryDistributionDTO deliveryDistributionDTO,HttpServletRequest request) {
        try {
            deliveryDistributionDTO.setGroupCode(UserUtil.getBranchCode());
            DeliveryDistributionVO deliveryDistributionVoSum = iDeliveryDistributionService.queryListSum(deliveryDistributionDTO);
            List<DeliveryDistributionVO> deliveryDistributionVOList = iDeliveryDistributionService.queryList(deliveryDistributionDTO);

            Page returnPage = new Page(deliveryDistributionDTO.getPageNum(),deliveryDistributionDTO.getPageSize());
            returnPage.setRecords(deliveryDistributionVOList);
            returnPage.setTotal(deliveryDistributionVoSum.getTotal());
            returnPage.setSumObject(deliveryDistributionVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 添加 出货分配
     *
     * @param deliveryItemVO
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 出货分配 ", notes = "添加 出货分配 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/save")
    public Result create(@RequestBody DeliveryItemVO deliveryItemVO, HttpServletRequest request) {
        try {
            deliveryItemVO.setGroupCode(UserUtil.getBranchCode());
            Result result = iDeliveryDistributionService.batchSave(deliveryItemVO);
            if(!result.isOk()){
                return result;
            }
            return Result.ok("分配成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取出货分配详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取出货分配详情", notes = "获取出货分配详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "出货分配code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DeliveryDistribution.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result deliveryDistribution(@PathVariable String code, HttpServletRequest request) {
        try {
            DeliveryDistribution entity = iDeliveryDistributionService.getOne(new QueryWrapper<DeliveryDistribution>().lambda().eq(DeliveryDistribution::getCode,code).eq(DeliveryDistribution::getGroupCode,UserUtil.getBranchCode()));
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改出货分配
     *
     * @param entity 出货分配
     * @param request
     * @return
     */
    @ApiOperation(value = "修改出货分配", notes = "修改出货分配")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/update")
    public Result update(DeliveryDistribution entity,HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iDeliveryDistributionService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 出货分配
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 出货分配 ", notes = "删除 出货分配 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "batchDel")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iDeliveryDistributionService.remove(new QueryWrapper<DeliveryDistribution>().lambda().in(DeliveryDistribution::getCode,codes).eq(DeliveryDistribution::getGroupCode,UserUtil.getBranchCode()));
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 拣货缺货
     *
     * @param request 出货分配
     * @return
     */
    @ApiOperation(value = "拣货缺货", notes = "拣货缺货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/stockOut")
    public Result stockOut(@RequestBody ReqPickMultiStockout request) {
        /*try{
            List<PickingRegister> pickingRegisters = iDeliveryDistributionService.updateDeliveryDistributions(request.getEntitys(),
                    false,request.getWavePickingCode(),request.getInventoryCode());
            //缺货登记执行到最后一条时，触发批量拣货确认操作
            if (IterUtil.isEmpty(pickingRegisters)) {
                Picking picking = pickingService.getOne(new LambdaQueryWrapper<Picking>().eq(Picking::getWavePickingCode, request.getWavePickingCode()));
                //批量拣货确认
                pickingService.PCBatchCheck(picking.getCode(),true);
            }
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }*/


        boolean bool = wavePickingConfirmationService.wavePickingOutStockRegistration(request.getEntitys(),
                request.getWavePickingCode(),request.getInventoryCode());
        //缺货登记执行到最后一条时，触发批量拣货确认操作
        if (bool) {
            Picking picking = pickingService.getOne(new LambdaQueryWrapper<Picking>().eq(Picking::getWavePickingCode, request.getWavePickingCode()).eq(Picking::getGroupCode,UserUtil.getBranchCode()));
            //批量拣货确认
            wavePickingConfirmationService.wavePicking(picking.getCode(),false,UserUtil.getBranchCode());
        }
        return Result.ok();


    }

    /**
     * 复核缺货
     *
     * @param request 复核缺货
     * @return
     */
    @ApiOperation(value = "复核缺货", notes = "修改出货分配、发货单明细、发货单等信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/recheckStockOut")
    public Result recheckStockOut(@RequestBody ReqPickMultiStockout request) {
        return iDeliveryDistributionService.recheckStockOut(request.getEntitys(),request.getWavePickingCode(),request.getInventoryCode(),false);
    }
}
